const http = require('http')
const queryString = require('querystring')

const server = http.createServer((req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    const query = queryString.parse(url.split('?')[1])
    // 设置响应的数据格式
    res.setHeader('Content-Type', 'application/json')
    // 定义返回的数据
    const resData = {
        method,
        url,
        path,
        query
    }

    // 处理Get请求
    if (method === 'GET') {
        res.end(JSON.stringify(resData))
    }

    // 处理Post请求
    if (method === 'POST') {
        // 请求的数据格式
        console.log(req.headers)
        // 接收数据
        let postData = ''
        req.on('data', chunk => postData += chunk)
        req.on('end', () => {
            res.end(JSON.stringify(resData))
        })
    }
})

server.listen(3000, () => {
    console.log('Listening on port 3000')
})
